<!--
 * @Author: wangming
 * @Date: 2020-09-09 14:04:55
 * @LastEditors: wangming
 * @LastEditTime: 2021-04-02 14:04:13
 * @Description:计算器
-->
<template>
  <el-dialog :visible="showVisible" :show-close="false" width="600px">
    <div class="b g3 f16 pl15 pr15" slot="title">
      <div class="ks-row-between">
        <span v-if="!flag">编辑统计值公式</span>
        <span v-else>编辑字段值公式</span>
        <span
          class="el-icon-close g9 f26 poi"
          @click="showVisible = false"
        ></span>
      </div>
    </div>
    <el-form
      class="pl20 pr20"
      :model="FormTypeData"
      ref="typeForm"
      label-width="100px"
      label-position="left"
      :rules="rules"
    >
      <el-form-item label="公式" prop="formulaList" required>
        <div class="textbox layoutbox g9 f14 sz lh1">
          <div class="ks-col">{{ showText }}</div>
          <div class="tr ks-row-middle lh1">
            <span class="ks-col"></span>
            <img
              src="@/assets/image/icon_huishan.svg"
              width="24"
              class="poi"
              @click="FormTypeData.formulaList.pop()"
            />
            <span class="f12 ml10 poi" @click="FormTypeData.formulaList = []"
              >清空</span
            >
          </div>
        </div>
      </el-form-item>
      <el-form-item v-if="!flag">
        <div slot="label" class="ks-row-middle">
          <span class="mr5">统计值</span>
        </div>
        <div
          class="tagbtn f14 g6 tc dib poi"
          @click="
            addModel({
              label: 'value',
              type: 'component',
            })
          "
        >
          value
        </div>
      </el-form-item>
      <el-form-item v-else>
        <div slot="label" class="ks-row-middle">
          <span class="mr5">模型字段</span>
        </div>
        <div
          class="tagbtn f14 g6 tc dib poi"
          v-for="i in columnList"
          :key="i.code"
          @click="addModel({ label: i.name,key:i.code,type: 'component' })"
        >
          {{ i.name }}
        </div>
      </el-form-item>
      <el-form-item label="符号">
        <div
          class="tagbtn f14 g6 tc dib poi"
          v-for="i in symbolList"
          :key="i"
          @click="addModel({ label: i, type: 'symbol' })"
        >
          {{ i }}
        </div>
        <div
          class="tagbtn f14 g6 tc dib poi"
          v-for="i in bracketsList"
          :key="i"
          @click="addModel({ label: i })"
        >
          {{ i }}
        </div>
      </el-form-item>
      <el-form-item label="数字">
        <div
          class="tagbtn f14 g6 tc dib poi"
          v-for="i in 9"
          :key="i"
          @click="addModel({ label: i, type: 'number' })"
        >
          {{ i }}
        </div>
        <div
          class="tagbtn f14 g6 tc dib poi"
          @click="addModel({ label: '0', type: 'number' })"
        >
          0
        </div>
        <div class="tagbtn f14 g6 tc dib poi" @click="addModel({ label: '.' })">
          .
        </div>
      </el-form-item>
      <el-form-item label="前缀" v-if="!flag">
        <el-input
          class="custom-symbol"
          placeholder="前缀"
          :maxlength="64"
          v-model="prefix"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="后缀" v-if="!flag">
        <el-input
          class="custom-symbol"
          placeholder="后缀"
          :maxlength="64"
          v-model="suffix"
        >
        </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="showVisible = false">取 消</el-button>
      <el-button type="primary" @click="addTypeBox">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { cloneDeep } from "lodash";
export default {
  computed: {
    showText() {
      return this.FormTypeData.formulaList.reduce((total, curr) => {
        return total + "" + curr.label;
      }, "");
    },
  },
  data() {
    return {
      rules: {
        formulaList: [
          {
            validator: (rule, value, callback) => {
              if (value.length === 0) {
                callback(
                  new Error("编辑的计算公式为空或不符合计算法则，无法计算")
                );
                return;
              }
              for (let i = 0; i < value.length; i++) {
                if (value[i].type == "component") {
                  if (
                    value[i - 1]?.type == "component" ||
                    value[i + 1]?.type == "component" ||
                    value[i - 1]?.label == "." ||
                    value[i + 1]?.label == "." ||
                    value[i + 1]?.type == "number" ||
                    value[i - 1]?.type == "number"
                  ) {
                    callback(
                      new Error("编辑的计算公式为空或不符合计算法则，无法计算")
                    );
                    break;
                  }
                }
              }
              let str = value.reduce((total, curr) => {
                let label = !!curr.key ? 1 : curr.label;
                return total + "" + label;
              }, "");
              try {
                eval(str);
                callback();
              } catch (error) {
                callback(
                  new Error("编辑的计算公式为空或不符合计算法则，无法计算")
                );
              }
            },
          },
        ],
      },
      symbolList: ["+", "-", "*", "/"],
      bracketsList: ["(", ")"],
      showVisible: false,
      prefix: "",
      suffix: "",
      FormTypeData: { formulaList: [] },
      callback: () => {},
      flag: undefined,
      columnList: [],
    };
  },
  methods: {
    addModel({ key, label, type }) {
      this.FormTypeData.formulaList.push({ label, key, type });
    },
    openFormula(formulaList, prefix, suffix, flag, numColumnList) {
      formulaList !== undefined
        ? (this.FormTypeData.formulaList = cloneDeep(formulaList))
        : (this.FormTypeData.formulaList = []);
      prefix !== undefined ? (this.prefix = prefix) : (this.prefix = "");
      suffix !== undefined ? (this.suffix = suffix) : (this.suffix = "");
      this.columnList = numColumnList;
      this.flag = flag;
      this.showVisible = true;
      this.$nextTick(() => {
        this.$refs.typeForm.clearValidate();
      });
      return {
        then: (callback) => {
          if (typeof callback === "function") {
            this.callback = callback;
          }
        },
      };
    },
    addTypeBox() {
      this.$refs.typeForm.validate((f) => {
        if (f) {
          this.showVisible = false;
          this.callback(
            this.FormTypeData.formulaList,
            this.prefix,
            this.suffix,
            this.showText
          );
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.bline {
  border-bottom: 1px solid #f1f1f1;
}
.tagbtn {
  height: 32px;
  line-height: 32px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-left: 12px;
  margin-bottom: 12px;
  padding: 0 16px;
  user-select: none;
}
.textbox {
  display: flex;
  flex-direction: column;
  width: 400px;
  height: 62px;
  padding: 8px 12px;
}
.custom-symbol {
  width: 240px;
  margin-bottom: 10px;
}
</style>
